import Vue from 'vue'
import Vuex from 'vuex'
import {reqAutoLogin} from '../api/res_login'
import {reqProfileInfo} from '../api/profile'
import { RECEIVE_ERRORS, CLEAR_ERRORS, RECEIVE_TOKEN,RECEIVE_USER, RESET_TOKEN, RESET_USER, UPDATE_USER } from './mutations-types'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    errors: {},
    token: '',
    user: {},
    followUser:[]
  },
  mutations: {
    [RECEIVE_ERRORS](state, err) {
      state.errors = err
    },
    [CLEAR_ERRORS](state){
      state.errors = {}
    },
    [RECEIVE_USER](state, user){
      state.user = user
    },
    [RESET_USER](state){
      state.user = {}
    },
    [RECEIVE_TOKEN](state, token){
      state.token = token
    },
    [RESET_TOKEN](state){
      state.token = ''
    },
    [UPDATE_USER](state, user){
      state.user = user
    },
  },
  actions: {
    // 提示错误消息
    errors({ commit, state }, err) {
      commit(RECEIVE_ERRORS, err)
    },

    // 清除错误消息
    clearErrors({ commit, state }) {
      commit(CLEAR_ERRORS)
    },

    saveUser({commit}, user){
      // 取出token单独保存
      const token = user.token
      commit(RECEIVE_TOKEN, token)
      // 存储到localStorage中
      window.sessionStorage.setItem('token_key', JSON.stringify(token))
      window.sessionStorage.setItem('user', JSON.stringify(user))
  
      delete user.token
      commit(RECEIVE_USER, user)
    },

    // 同步清除用户信息
    resetUser({commit}){
      commit(RESET_USER)
      commit(RESET_TOKEN)
      // 清除内存中的token
      window.sessionStorage.removeItem('token_key')
      window.sessionStorage.removeItem('user')
    },

    // 自动登录
    async autoLogin({commit}){
      const token = sessionStorage.getItem('token_key')
      if(token){
        const result = await reqAutoLogin()
        // if(result.code === 0){
          const user = result.user
          commit(RECEIVE_USER, user)
        // }
      }
    },


    // 更新用户信息
    async updataUser({commit}, user){
      const result = await reqProfileInfo(user)
      commit(UPDATE_USER, result.user)
    }
  },
  modules: {
  }
})
